﻿using Microsoft.Office.Core;
using Microsoft.Office.Tools;
using Microsoft.Office.Tools.Excel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;

namespace ExcelAddIn1
{
    public static class Common
    {
        public static Excel.Application ExcelApp;
        public static CommandBar cmb;
        public static ActionsPane acp;
        //上述这个，是最重要的对象，
    }

    // 数据模型
    public class DebugOutputModel : INotifyPropertyChanged
    {
        private StringBuilder _outputBuilder = new StringBuilder();
        private string _debugOutput = string.Empty;

        public string DebugOutput
        {
            get { return _debugOutput; }
            set
            {
                _debugOutput = value;
                OnPropertyChanged(nameof(DebugOutput));
            }
        }

        public void AppendDebugLine(string message)
        {
            _outputBuilder.AppendLine($"{DateTime.Now:HH:mm:ss.fff} - {message}");

            // 限制输出长度
            if (_outputBuilder.Length > 10000)
            {
                _outputBuilder.Remove(0, _outputBuilder.Length - 5000);
            }

            DebugOutput = _outputBuilder.ToString();
        }

        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    // 自定义TraceListener
    public class BindingSourceTraceListener : TraceListener
    {
        private DebugOutputModel _debugModel;

        public BindingSourceTraceListener(DebugOutputModel debugModel)
        {
            _debugModel = debugModel;
        }

        public override void Write(string message)
        {
            _debugModel.AppendDebugLine(message);
        }

        public override void WriteLine(string message)
        {
            _debugModel.AppendDebugLine(message);
        }
    }
}
